package com.lnj.messages.servise;

import com.lnj.messages.quarzJob.ESVectorJob;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class ESVectorService {
    @Autowired
    private final Scheduler quartzScheduler;

    /**
     * 服务启动时初始化定时任务
     */
    @PostConstruct
    public void initScheduledTask() {
        try {
            // 创建任务详情
            JobDetail job = JobBuilder.newJob(ESVectorJob.class)
                    .withIdentity("esVectorJob", "esVectorGroup")
                    .build();

            // 创建触发器 - 每天下午5点30分执行
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("esVectorTrigger", "esVectorGroup")
                    .withSchedule(CronScheduleBuilder.cronSchedule("0 32 13 * * ?"))
                    .build();

            // 检查任务是否已存在，避免重复注册
            if (quartzScheduler.checkExists(job.getKey())) {
                quartzScheduler.deleteJob(job.getKey());
            }

            // 调度任务
            quartzScheduler.scheduleJob(job, trigger);

            log.info("ES向量服务定时任务已启动，每天下午5点30分执行");
        } catch (SchedulerException e) {
            log.error("初始化ES向量服务定时任务失败", e);
        }
    }
}
